#include "smallsh.h"

int runcommand(char** cline, int where)
{
    int pid,exitstat,ret;

    if( (pid=fork()) < 0) {
        perror("fork failed");
        return(-1);
    }
    if(!pid) { // 子进程
        execvp(*cline,cline); // *cline指向的是cline[]数组的第一个元素，即要执行的文件/命令路径
        // **cline = arg *cline = arg这个指针所指向的内容 = *arg
        // *arg代表数组的第一个元素
        // &(*arg) = arg


        /*
       int execvp(const char *file, char *const argv[]);

       The  execv(),  execvp(),  and execvpe() functions provide an array of pointers to null-terminated strings that represent the argument list available to the new pro‐
       gram.  The first argument, by convention, should point to the filename associated with the file being executed.  The array of pointers must be terminated by a  null
       pointer.
       functions, this pointer must be cast (char *) NULL.

    Special semantics for execlp() and execvp()
       The  execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an executable file if the specified filename does not contain a
       slash (/) character.  The file is sought in the colon-separated list of directory pathnames specified in the PATH environment  variable.   If  this  variable  isn't
       defined, the path list defaults to the current directory followed by the list of directories returned by confstr(_CS_PATH).  (This confstr(3) call typically returns
       the value "/bin:/usr/bin".)
        */
        perror(*cline);
        exit(127);
    }

    // 父进程
    // 后台进程
    if(where == BACKGROUND) {
        printf("[process id %d]\n",pid);
        return(0);
    }

    // 前台进程
    while((ret = wait(&exitstat)) != pid && ret != -1); // 等待所有子进程正常退出？
    // 只有最后被启动的子进程结束时，runcommand才结束，避免了后台命令中途结束带来的问题

    return(ret==-1?-1:exitstat);
}